/**
 * Copyright (c) Software Institute of PKU
 * All rights reserved. 
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 */
package edu.pku.sei.modeler.ui.dnd;

import java.util.List;

import org.eclipse.gef.EditPartViewer;
import org.eclipse.gef.Request;
import org.eclipse.gef.RequestConstants;
import org.eclipse.gef.dnd.AbstractTransferDropTargetListener;
import org.eclipse.gef.dnd.TemplateTransfer;
import org.eclipse.gef.requests.CreateRequest;
import org.eclipse.swt.dnd.DND;
import org.eclipse.swt.dnd.DropTargetEvent;

import edu.pku.sei.modeler.model.core.MetaModel;
import edu.pku.sei.modeler.model.core.MetaModelElement;

/**
 * @author zl
 * 
 */
public class MetaElementDropTargetListener extends
		AbstractTransferDropTargetListener {
	private DropElementCreationFactory factory;
	public MetaElementDropTargetListener(EditPartViewer viewer, MetaModel model) {
		super(viewer);
		try {
			factory = new DropElementCreationFactory();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		this.setTransfer(TemplateTransfer.getInstance());
	}
	
	protected Request createTargetRequest() {
		CreateRequest request = new CreateRequest(RequestConstants.REQ_ADD);
		request.setFactory(factory);
		if (getCurrentEvent().data != null) {
			if (getCurrentEvent().data instanceof MetaModelElement)
				factory.addElement((MetaModelElement) getCurrentEvent().data);
			else if (getCurrentEvent().data instanceof List) {
				factory.setElements((List)getCurrentEvent().data);
			}
		}
		return request;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.gef.dnd.AbstractTransferDropTargetListener#updateTargetRequest()
	 */
	@Override
	protected void updateTargetRequest() {
		((CreateRequest) getTargetRequest()).setLocation(getDropLocation());
	}

	@Override
	public boolean isEnabled(DropTargetEvent event) {
		return true;
	}
	
	protected void handleDragOver() {
		getCurrentEvent().detail = DND.DROP_COPY;
		super.handleDragOver();
	}

}
